public class LongestValidParentheses {
    public int longestValidParentheses(String s) {
        // 滑动窗口
        // leftCount记录窗口中左括号的数量
        int leftCount = 0;
        // rightCount记录窗口中右括号的数量
        int rightCount = 0;
        char[] arr = s.toCharArray();
        int maxLength = 0;
        for (int left = 0, right = 0; right < arr.length; right++) {
            if (arr[right] == '(') {
                leftCount++;
            } else {
                rightCount++;
            }
            if (leftCount == rightCount && rightCount != 0) {
                maxLength = Math.max(maxLength, Math.min(leftCount, rightCount) * 2);
            }
            while (rightCount > leftCount && left <= right) {
                if (arr[left++] == '(') {
                    leftCount--;
                } else {
                    rightCount--;
                }
            }
        }
        if (maxLength == 0) {
            maxLength = Math.max(maxLength, Math.min(leftCount, rightCount) * 2);
        }
        return maxLength;
    }

    public static void main(String[] args) {
        System.out.println(new LongestValidParentheses().longestValidParentheses("(()(((()"));
    }
}
